package com.isoft.service;

import com.isoft.entity.Authority;
import com.isoft.entity.Customer;
import com.isoft.repository.AuthorityService;
import com.isoft.repository.CustomerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author LiuGaoMing
 * @version 1.0
 * @description:
 * @date 2024/5/17 9:44
 */
@Service
public class CustomerService {
    @Autowired
    private CustomerRepository customerRepository;
    @Autowired
    private AuthorityService authorityService;
    @Autowired
    private RedisTemplate redisTemplate;
//    获取用户信息更具用用户名，使用redis进行优化
    public Customer getCustomer(String username){
        Customer customer = null;
        Object obj = redisTemplate.opsForValue().get("customer_" + username);
        if(obj == null){
//            说明是第一次
            customer = customerRepository.findByUsername(username);
            if(customer != null){
                redisTemplate.opsForValue().set("customer_" + username,customer);
            }
        }else {
            customer = (Customer) obj;
        }
        return customer;
    }

    public List<Authority> getCustomerAuthorities(String username){
        List<Authority> authorities = null;
        Object obj = redisTemplate.opsForValue().get("authorities_" + username);
        if(obj == null){
//            说明是第一次
            authorities = authorityService.findAuthoritiesByUsername(username);
            if(authorities.size()>0){
                redisTemplate.opsForValue().set("authorities_" + username,authorities);
            }
        }else {
            authorities = (List<Authority>) obj;
        }
        return authorities;
    }

}
